import React, { PropTypes } from 'react';
import { Button, Form, Select, Input, Collapse, Checkbox, Row, Col, Steps, Tag } from 'antd';
import Highlight from 'react-highlight';

import { selectOptions, radioOptions, formatJson, fieldsToParams } from 'src/utils/transform';
import FormModal from 'components/decorator/formModal';
import { systemConstants } from 'src/utils/constants';

import 'css/highlight.css';
import './detailForm.less';

const Panel = Collapse.Panel;
const Option = Select.Option;
const FormItem = Form.Item;
const Step = Steps.Step;

class DetailForm extends React.Component {

  outputFullAPIDemo = () => {
    this.outputAPIDemo('full');
  }

  outputIncAPIDemo = () => {
    this.outputAPIDemo('inc');
  }

  outputIncCallback = () => {
    this.outputAPIDemo('incCallback');
  }

  outputAPIDemo = (type) => {
    const { entity } = fieldsToParams(this.props.form.getFieldsValue());
    const indexId = this.props.relatedData.indexData.id;
    this.props.onOutputAPIDemo({ entity, type, indexId });
  }

  triggerFullTest = () => {
    this.triggerTest('full');
  }

  triggerIncTest = () => {
    this.triggerTest('incCallback');
  }

  triggerTest = (type) => {
    const { entity, fullTestRequest, incTestRequest } = fieldsToParams(this.props.form.getFieldsValue());
    let indexId = this.props.relatedData.indexData.id;
    this.props.onTriggerTest({ entity, type, indexId, fullTestRequest, incTestRequest });
  }

  render() {

    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 16 },
    };

    const inlineFormItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 12 },
      style: { display: 'inline-block', verticalAlign: 'top', marginBottom: 0 }
    };

    const {
      entity,
      fullApiDemoResponse, fullTestResponse,
      incCallbackDemoResponse, incApiDemoResponse, incTestResponse
    } = this.props;

    const incDatasourceTypeOptions = radioOptions(systemConstants.incDatasourceType);

    const fullSteps = [{
      title: '查看实例API',
      description: '根据左侧参数生成API实例',
    }, {
      title: '请求测试',
      description: '执行实例API',
    },{
      title: '结果展示',
      description: '生成真实结果',
    }];


    const incSteps = [{
      title: '增量推送',
      description: '增量推送方式展示',
    },{
      title: '增量反查示例',
      description: '根据左侧参数生成API实例',
    },{
      title: '请求测试',
      description: '执行实例API',
    },{
      title: '结果展示',
      description: '生成真实结果',
    }];


    return (
      <Form>
        <FormItem
          wrapperCol= {{ span: 6 }}
        >
          {
            getFieldDecorator('entity.name', {
              initialValue: entity ? entity.name : '',
            })(
              <Input placeholder="数据源名称" />,
            )
          }
        </FormItem>
        <Collapse defaultActiveKey={['fullDatasource']}>
          <Panel header="全量导入" key="fullDatasource">
            <Row>
              <Col span={8}>
                <FormItem
                  {...formItemLayout}
                  label="导入通道"
                >
                  {
                    getFieldDecorator('entity.fullDatasourceType', {
                      initialValue: entity.fullDatasourceType ? '' + entity.fullDatasourceType : '0',
                    })(
                      <Select style={{ width: '150px' }}>
                        { selectOptions(systemConstants.datasource.datasourceTypes) }
                      </Select>,
                    )
                  }
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="地址"
                >
                  {
                    getFieldDecorator('entity.fullDatasourceRpc.rpcUrl', {
                      initialValue: entity.fullDatasourceRpc ? entity.fullDatasourceRpc.rpcUrl : '',
                    })(
                      <Input placeholder="" />,
                    )
                  }
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="RPC方法"
                >
                  {
                    getFieldDecorator('entity.fullDatasourceRpc.rpcMethod', {
                      initialValue: entity.fullDatasourceRpc ? entity.fullDatasourceRpc.rpcMethod : '',
                    })(
                      <Input placeholder="" />,
                    )
                  }
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="分页大小"
                >
                  {
                    getFieldDecorator('entity.fullDatasourceRpc.pageSize', {
                      initialValue: entity.fullDatasourceRpc ? entity.fullDatasourceRpc.pageSize : '',
                    })(
                      <Input placeholder="" />,
                    )
                  }
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="起始页码"
                >
                  {
                    getFieldDecorator('entity.fullDatasourceRpc.startPage', {
                      initialValue: entity.fullDatasourceRpc ? entity.fullDatasourceRpc.startPage : '',
                    })(
                      <Input placeholder="" />,
                    )
                  }
                </FormItem>
              </Col>
              <Col span={16}>
                  <Steps current={ this.props.currentFullStep || 0 } style={{ marginBottom: 10 }}>
                    {fullSteps.map(item => <Step key={item.title} title={item.title} description={item.description} />)}
                  </Steps>
                  {
                    (this.props.currentFullStep === undefined || this.props.currentFullStep === 0)
                    &&
                    <Button type="primary" size={ 'default' } onClick={ this.outputFullAPIDemo }>查看API示例</Button>
                  }
                  {
                    this.props.currentFullStep === 1
                    &&
                    <Button type="primary" size={ 'default' } onClick={ this.triggerFullTest } style={{ marginLeft: 10 }}>请求测试</Button>
                  }
                  {
                    (this.props.currentFullStep !== undefined &&  this.props.currentFullStep !== 0)
                    &&
                    <Button type="primary" size={ 'default' } onClick={ this.props.clearFullApiResults } style={{ marginLeft: 10 }}>重置</Button>
                  }
                  {
                    this.props.currentFullStep === 1
                    &&
                    <div style={{ marginTop: 10 }}>
                    <FormItem
                      {...inlineFormItemLayout}
                      label="before"
                    >
                      {
                        getFieldDecorator('fullTestRequest.before', {
                        })(
                          <Input placeholder="" />,
                        )
                      }
                    </FormItem>
                    <FormItem
                      {...inlineFormItemLayout}
                      label="pageNo"
                    >
                      {
                        getFieldDecorator('fullTestRequest.pageNo', {
                        })(
                          <Input placeholder="" />,
                        )
                      }
                    </FormItem>
                    </div>
                  }
                  <div className="http-response-container">
                  {
                    (() => {
                      if (fullApiDemoResponse.url) {
                         return <div><p className="http-response-title">URL: { fullApiDemoResponse.url }</p>
                          <p className="http-response-title">请求:</p>
                          <Highlight>
                              { fullApiDemoResponse.request ? formatJson(fullApiDemoResponse.request) : '' }
                          </Highlight>
                          <p className="http-response-title">响应:</p>
                          <Highlight>
                              { fullApiDemoResponse.response ? formatJson(fullApiDemoResponse.response) : '' }
                          </Highlight></div>
                      }
                      else if (fullTestResponse.success !== undefined) {
                         return <div><p className="http-response-title">
                         状态: { fullTestResponse.success ? <Tag color="green">成功</Tag> : <Tag color="red">失败</Tag>  }
                         </p>
                          <p className="http-response-title">响应:</p>
                          <Highlight>
                              { fullTestResponse.data ? formatJson(fullTestResponse.data) : fullTestResponse.errorMessage }
                          </Highlight></div>
                      }
                    })()
                  }
                  </div>
              </Col>
            </Row>
          </Panel>
        </Collapse>
        <FormItem
          labelCol={{ span: 3 }}
          wrapperCol= {{ span: 16 }}>
            <Checkbox
              onChange={this.props.onIncDatasourceTypeChange}
              checked={entity.useIncImport}>配置增量导入</Checkbox>
        </FormItem>
        {
          entity.useIncImport
          &&
          <Collapse defaultActiveKey={['incDatasource']}>
            <Panel header="增量导入" key="incDatasource">
              <Row>
                <Col span={8}>
                  <FormItem
                    {...formItemLayout}
                    label="导入通道"
                  >
                    {
                      getFieldDecorator('entity.incDatasourceType', {
                        initialValue: entity.incDatasourceType ? '' + entity.incDatasourceType : '0',
                      })(
                        <Select style={{ width: '150px' }}>
                          { selectOptions(systemConstants.datasource.datasourceTypes) }
                        </Select>,
                      )
                    }
                  </FormItem>
                  <FormItem
                    {...formItemLayout}
                    label="RPC方法"
                  >
                    {
                      getFieldDecorator('entity.incDatasourceRpc.rpcMethod', {
                        initialValue: entity.incDatasourceRpc ? entity.incDatasourceRpc.rpcMethod : '',
                      })(
                        <Input placeholder="" />,
                      )
                    }
                  </FormItem>
                  <FormItem
                    {...formItemLayout}
                    label="回调地址"
                  >
                    {
                      getFieldDecorator('entity.incDatasourceRpc.rpcUrl', {
                        initialValue: entity.incDatasourceRpc ? entity.incDatasourceRpc.rpcUrl : '',
                      })(
                        <Input placeholder="" />,
                      )
                    }
                  </FormItem>
                </Col>
                <Col span={16}>
                    <Steps current={ this.props.currentIncStep || 0 } style={{ marginBottom: 10 }}>
                      {incSteps.map(item => <Step key={item.title} title={item.title} description={item.description} />)}
                    </Steps>
                    {
                      (this.props.currentIncStep === undefined || this.props.currentIncStep === 0)
                      &&
                      <Button type="primary" size={ 'default' } onClick={ this.outputIncAPIDemo }>查看API示例</Button>
                    }
                    {
                      this.props.currentIncStep === 1
                      &&
                      <Button type="primary" size={ 'default' } onClick={ this.outputIncCallback } style={{ marginLeft: 10 }}>执行回调</Button>
                    }
                    {
                      this.props.currentIncStep === 2
                      &&
                      <Button type="primary" size={ 'default' } onClick={ this.triggerIncTest } style={{ marginLeft: 10 }}>请求测试</Button>
                    }
                    {
                      this.props.currentIncStep === 2
                      &&
                      <div style={{ display: 'inline-block', verticalAlign: 'middle' }}>
                      <FormItem
                        {...inlineFormItemLayout}
                        label="id列表"
                      >
                        {
                          getFieldDecorator('incTestRequest.entityIdList', {})(
                            <Input type="textarea" rows={4}/>
                          )
                        }
                      </FormItem>
                      </div>
                    }
                    {
                      (this.props.currentIncStep !== undefined &&  this.props.currentIncStep !== 0)
                      &&
                      <Button type="primary" size={ 'default' } onClick={ this.props.clearIncApiResults } style={{ marginLeft: 10 }}>重置</Button>
                    }
                    <div className="http-response-container">
                    {
                      (() => {
                        if (incApiDemoResponse.url) {
                           return <div><p className="http-response-title">URL: { incApiDemoResponse.url }</p>
                            <p className="http-response-title">请求:</p>
                            <Highlight>
                                { incApiDemoResponse.request ? formatJson(incApiDemoResponse.request) : '' }
                            </Highlight>
                            <p className="http-response-title">响应:</p>
                            <Highlight>
                                { incApiDemoResponse.response ? formatJson(incApiDemoResponse.response) : '' }
                            </Highlight></div>
                        }
                        else if (incCallbackDemoResponse.request) {
                           return <div><p className="http-response-title">响应:</p>
                            <Highlight>
                                { incCallbackDemoResponse.request ? formatJson(incCallbackDemoResponse.request) : '' }
                            </Highlight></div>
                        }
                        else if (incTestResponse.success !== undefined) {
                           return <div><p className="http-response-title">
                           状态: { incTestResponse.success ? <Tag color="green">成功</Tag> : <Tag color="red">失败</Tag>  }
                           </p>
                            <p className="http-response-title">响应:</p>
                            <Highlight>
                                { incTestResponse.data ? formatJson(incTestResponse.data) : incTestResponse.errorMessage }
                            </Highlight></div>
                        }
                      })()
                    }
                    </div>
                </Col>
              </Row>
            </Panel>
          </Collapse>
        }
      </Form>
    );
  }
}
export default Form.create()(FormModal(DetailForm));
